<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$emit('nextPage', pageNo - 1)">
      上一页
    </button>
    <!-- 起始页大于1时 -->
    <button
      v-show="startingPoint.start > 1"
      :class="{ active: pageNo === 1 }"
      @click="$emit('nextPage', 1)"
    >
      1
    </button>
    <!-- 起始页大于2时 -->
    <button v-show="startingPoint.start > 2">···</button>

    <button
      v-for="page in startEnd"
      :key="page"
      @click="$emit('nextPage', page)"
      :class="{ active: pageNo === page }"
    >
      {{ page }}
    </button>

    <button v-show="startingPoint.end < totalPages - 1">···</button>
    <button
      v-show="startingPoint.end < totalPages"
      @click="$emit('nextPage', totalPages)"
    >
      {{ totalPages }}
    </button>
    <button
      :disabled="pageNo === totalPages"
      @click="$emit('nextPage', pageNo + 1)"
    >
      下一页
    </button>
    <button style="margin-left: 30px">共{{ total }}条</button>
  </div>
</template>
<script>
export default {
  name: "Pagination",
  props: ["pageNo", "totalPages", "continueNum", "total"],
  computed: {
    startingPoint() {
      // pageNo 当前页数 totalPages 总页数 continueNum 连续页
      const { pageNo, totalPages, continueNum } = this;
      let start = 0;
      let end = 0;
      // 如果连续页大于总页数
      if (totalPages < continueNum) {
        start = 1;
        end = totalPages;
      } else {
        // 起始页
        start = pageNo - Math.floor(continueNum / 2);
        // 终止页
        end = pageNo + Math.floor(continueNum / 2);
        // 如果起始页小于默认起始页(1)
        if (start < 1) {
          start = 1;
          end = continueNum;
        }
        // 如果终止页大于实际总页数
        if (end > totalPages) {
          end = totalPages;
          start = totalPages - continueNum + 1;
        }
      }
      return { start, end };
    },
    /* 
      永远不要把 v-if 和 v-for 同时用在同一个元素上
        - 因为v-for的优先级高于v-if
        - 先遍历生成结构,然后再判断去掉某些结构,对性能来说不友好
        - 解决方法:1.把v-for遍历的数据用计算数据先行过滤   2. 多增添一层结构分开书写v-if和v-for
    */
    startEnd() {
      const arr = [];
      for (let i = 1; i <= this.startingPoint.end; i++) {
        if (i >= this.startingPoint.start) {
          arr.push(i);
        }
      }
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
